<?php

namespace App\Http\Controllers\Check;

use App\App\Services\Web\UserService;
use App\Contracts\Repositories\ActivityRepository as ActivityRepositoryContact;
use App\Events\ActivityCommonCreated;
use App\Events\ActivityCommonUpdated;
use App\Entities\Activity;
use App\Entities\CheckRule;
use App\Entities\Check;
use App\Entities\ActivityModel;
use App\Http\Controllers\Activity\BaseController;
use App\Morefun\Publishing\Publisher;
use Carbon\Carbon;
use Illuminate\Container\Container;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class ActivityController extends BaseController
{
    protected $redis;

    public function __construct(UserService $user, ActivityRepositoryContact $activities)
    {
        parent::__construct($user, $activities);
        if(!$this->redis){
            $this->redis = Container::getInstance()->make('redis');
        }
    }

    public function show($id)
    {
        $activity = $this->activities->findOne($id);

        if (null === $activity) {
            return response()->failed('没有找到资源');
        }

        //$storage = Container::getInstance()->make(StorageServiceContract::class);

        $translated = [
            'id'               => $activity->id,
            'category'         => $activity->category,
            'name'             => $activity->name,
            'start_time'       => $activity->startTime,
            'end_time'         => $activity->endTime,
            //'background_img'   => $storage->toHttpUrl($activity->backgroundImg),
            'description'      => $activity->description,
            'app_url'          => $activity->app_url,
            'publishing'       => \GuzzleHttp\json_decode($activity->publishing_ways, true),
            'shares'           => $this->formatShares($activity->shares),
        ];

        $checkList   = CheckRule::query()->where('activity','=',$activity->id)->get()->toArray();

        return response()->success([
            'activity' => $translated,
            'list'       => $checkList
        ]);
    }

    public function update(Request $request, $id)
    {
        $activity = Activity::query()->where('id', $id)->first();
        if (null === $activity) {
            return response()->failed('没有找到这个活动');
        }
        $input = $request->json()->all();
        $validator = Validator::make($input, $this->getRulesForUpdate());
        if ($validator->fails()) {
            return response()->failed(Arr::first($validator->errors()->all()));
        }

        $input = $this->translateInputFromRequest($request);
        // 去掉不可修改的值
        Arr::forget($input, ['user_id', 'group_code', 'model_id', 'template_id']);
        $activity->fill($input);

        $database = Container::getInstance()->make('db');

        $success = $database->transaction(function () use ($activity,$input) {
            $activity->save();
            CheckRule::creat(parseLimits($input['check']));
            Check::creat($input);
            $info = ActivityInfo::query()->find($activity->getAttribute('id'));
            if (!$info) {
                return true;
            }

            $info->setAttribute('name', $activity->getAttribute('name'));
            return $info->save();
        });

        if ($success) {
            $this->redis->setex(
                'checks:'.$id,
                strtotime($input['end_time'])-time(),
                json_encode(
                    $input['check']
                )
            );

            $this->updatedEvents($activity);
            return response()->success();
        }

        return response()->failed('活动修改失败');
    }

    protected function getRulesForCreate()
    {
        return [
            'name'                 => 'required|max:255',
            'category'             => 'required|in:1,2',
            'start_time'           => 'required|date',
            'end_time'             => 'required|date|after:start_time',
            'model_id'             => 'required',
            'template_id'          => 'required',
            'description'          => 'min:1',
            //'validations'          => 'array',
            //'validations.type'     => 'in:IP,MOBILE,VERIFY_CODE,PASSWORD',
            //'validations.password' => 'required_if:validations.type,PASSWORD',
            'shares'               => 'array',
            'shares.title'         => 'required_if:shares.isopen,on',
            'shares.content'       => 'required_if:shares.isopen,on',
        ];
    }

    protected function getRulesForUpdate()
    {
        return [
            'name'                 => 'max:255',
            'category'             => 'in:1,2',
            'start_time'           => 'date',
            'end_time'             => 'date|after:startTime',
            'description'          => 'min:1',
            'check'                 => 'array',
//            'check_type'         =>'in:0,1',
//            'check_rule'            =>'in:0,1',
//            'check_count'        =>'Numeric',
//            'check_prize_id'           =>'uuid',
//            'check_prize_count'      =>'Numeric',
//            'is_while'               =>'in:0,1',

            //'validations'          => 'array',
            //'validations.type'     => 'in:IP,MOBILE,VERIFY_CODE,PASSWORD',
            //'validations.password' => 'required_if:validations.type,PASSWORD',
            //'relation'             => 'array',
            //'relation.id'          => 'uuid',
        ];
    }

    protected function parseRules(Request $request)
    {
        return json_encode([
            'validations' => $request->json('validations', []),
            // 关联其他活动
            'relation'    => ['id' => $request->get('relation.id', '')],
        ]);
    }

    protected function parseLimits(Request $request)
    {
        foreach ($request as &$v){
            $v = json_decode($v);
        }
        return $request;
    }

    protected function createdEvents(Activity $activity)
    {
        return event(new ActivityCommonCreated($activity));
    }

    protected function updatedEvents(Activity $activity)
    {
        return event(new ActivityCommonUpdated($activity));
    }
}
